var annotationsPanel = {
    id: "panel-annotations-control",
    title: "Annotations",
    bodyStyle: "padding-bottom:15px; background:#eee;",
    autoScroll: true,
    contentEl: "panel-annotations"
};

eventManager.registerNodeSelectListener(function(node) {
    displayAnnotations(node);
});

function displayAnnotations(node) {
    if (node.attributes.cls == "file" || node.attributes.cls == "folder") {
        Ext.Ajax.request({
            url: node.attributes.uri + "/annotations",
            success: function(response) {
                Ext.getDom("panel-annotations").innerHTML = "Annotations: " + response.responseText;
                var jsonObj = Ext.util.JSON.decode(response.responseText);
                renderAnnotationsGrid(jsonObj, node.attributes.uri);
                renderAnnotationsForm(node);
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Annotations Not Available", level: "error" });
            }
        });
    }
}

function renderAnnotationsGrid(jsonObj, uri) {
    Ext.getDom("panel-annotations").innerHTML = "";
    var annotationsGrid = new Ext.grid.PropertyGrid({
        renderTo: "panel-annotations",
        autoHeight: true,
        width: 320,
        selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
        source: jsonObj,
        tbar:[
            {
                text:'Delete',
                tooltip:'Delete selected annotation',
                handler : function() {
                    var recSelected = annotationsGrid.getSelectionModel().getSelected();
                    var postUrl = uri + "/annotations?JSON={" + recSelected.data.name + "='null'}";
                    Ext.Ajax.request({
                        url: postUrl,
                        method: "POST",
                        success: function() {
                            eventManager.fireStatusMessageEvent({ text: "Annotation Deleted", level: "info" });
                            annotationsGrid.store.remove(recSelected);
                        },
                        failure: function() {
                            eventManager.fireStatusMessageEvent({ text: "Deleting Annotation Failed", level: "error" });
                        }
                    });
                }
            },
            {
                text:'Save Updates',
                tooltip:'Save Annotation Changes',
                handler : function() {
                    var jsonToPost = {};
                    for (var i = 0; i < annotationsGrid.store.getCount(); i++) {
                        var rec = annotationsGrid.store.getAt(i);
                        var text = rec.data.value;
                        text = text + "";
                        if (text.indexOf(",") > 0) {
                            jsonToPost[rec.data.name] = text.split(",");
                        } else {
                            jsonToPost[rec.data.name] = text;
                        }
                    }
                    Ext.Ajax.request({
                        url: uri + "/annotations",
                        method: 'POST',
                        params: {
                            JSON: Ext.encode(jsonToPost)
                        },
                        success: function() {
                            eventManager.fireStatusMessageEvent({ text: "Annotations Updated", level: "info" });
                        },
                        failure: function() {
                            eventManager.fireStatusMessageEvent({ text: "Saving Annotations Failed", level: "error" });
                        }
                    });
                }
            }
        ]
    });
    annotationsGrid.render();
}

function renderAnnotationsForm(node) {
    var uri = node.attributes.uri;
    var annotationFormPanel = new Ext.form.FormPanel({
        id: 'annotationAddForm',
        method: 'POST',
        renderTo: "panel-annotations",
        border: false,
        items: [
            new Ext.form.FieldSet({
                autoHeight: true,
                autoWidth: true,
                border: false,
                items: [
                    new Ext.form.TextField({
                        fieldLabel: 'New annotation',
                        defaultAutoCreate : {tag:"input", size: "35", autocomplete: "off"},
                        name: 'newAnnotation',
                        id: 'newKeyId',
                        allowBlank: false
                    }),
                    new Ext.form.TextField({
                        fieldLabel: 'Value',
                        defaultAutoCreate : {tag:"input", size: "35", autocomplete: "off"},
                        name: 'newValue',
                        id: 'newValueId',
                        allowBlank: false
                    }),
                    new Ext.Button({
                        id: 'show-button',
                        text: 'Add',
                        listeners: {
                            click: function() {
                                var key = Ext.getCmp("newKeyId").getValue();
                                var value = Ext.getCmp("newValueId").getValue();
                                var postUrl = uri + "/annotations?JSON={" + key + "=" + value + "}";
                                Ext.Ajax.request({
                                    url: postUrl,
                                    method: "POST",
                                    success: function() {
                                        eventManager.fireStatusMessageEvent({ text: "Annotation Added Successfully", level: "info" });
                                        displayAnnotations(node);
                                    },
                                    failure: function() {
                                        eventManager.fireStatusMessageEvent({ text: "Adding Annotation Failed", level: "error" });
                                    }
                                });
                                displayAnnotations(node);
                            }
                        }
                    })
                ]
            })
        ]
    });
    annotationFormPanel.render();
}

var labelsPanel = new Ext.Panel({
    id: "panel-labels-control",
    title: "Family Tree",
    bodyStyle: "padding-bottom:15px; background:#eee;",
    autoScroll: true,
    collapsible: true,
    contentEl: "panel-labels"
});

//make the ajax call a function so we can call to rerender form
eventManager.registerNodeSelectListener(function(node) {
    if (node.attributes.cls == "file" || node.attributes.cls == "folder") {
        Ext.Ajax.request({
            url: node.attributes.uri + "/labels",
            success: function(response) {
                var jsonObj = Ext.util.JSON.decode(response.responseText);
                renderLabelGrid(jsonObj);
                renderLabelForm();
            },
            failure: function(response) {
                Ext.getDom("panel-labels").innerHTML = "Labels Not Available: " + response.responseText;
            }
        });
    }
});

function renderLabelGrid(jsonObj) {
    Ext.getDom("panel-labels").innerHTML = "";
    var labelGrid = new Ext.grid.PropertyGrid({
        renderTo: "panel-labels",
        autoHeight: true,
        //autoWidth: true,
        width: 320,
        disableSelection: true,
        startEditing: Ext.emptyFn,
        source: jsonObj
    });
    labelGrid.render();
}

function renderLabelForm() {
    var labelFormPanel = new Ext.form.FormPanel({
        id: 'uploadFileForm',
        method: 'POST',
        renderTo: "panel-labels",
        border: false,
        items: [
            new Ext.form.FieldSet({
                autoHeight: true,
                autoWidth: true,
                border: false,
                items: [
                    new Ext.form.TextField({
                        fieldLabel: 'New label',
                        defaultAutoCreate : {tag:"input", size: "20", autocomplete: "off"},
                        name: 'newlabel',
                        allowBlank: false
                    }),
                    new Ext.Button({
                        id: 'show-button',
                        text: 'Add',
                        listeners: {click: function() {
                            console.log("adding label");
                        }
                        }
                    })
                ]
            })
        ]
    });
    labelFormPanel.render();
}

var propertiesPanel = new Ext.Panel({
    id: "panel-properties-control",
    title: "Omics Data",
    bodyStyle: "padding-bottom:15px; background:#eee;",
    autoScroll: true,
    collapsible: true,
    contentEl: "panel-properties",
    items:{
        layout: 'hbox',
        width: 500,
        fieldLabel: 'S. cerevisiae?',
        msgTarget: 'under',
        items: [
            {
                xtype: 'displayfield',
                value: '&nbsp;Search:&nbsp;'
            },
            {
                xtype:'textfield',
                id: 'omicsinputid',
                name: 'omicsinput',
                anchor:'95%'
            },
            {
                xtype: 'button',
                text: '&nbsp;Go&nbsp;'
            }

        ]
    }
});


eventManager.registerNodeSelectListener(function(node) {
    if (node.attributes.cls == "file" || node.attributes.cls == "folder") {
        Ext.Ajax.request({
            url: node.attributes.uri + "/meta",
            success: function(response) {
                //Ext.getDom("panel-properties").innerHTML = "Properties: " + response.responseText;
                var jsonObj = Ext.util.JSON.decode(response.responseText);
                renderPropertyGrid(jsonObj);
            },
            failure: function(response) {
                Ext.getDom("panel-properties").innerHTML = "Properties Not Available: " + response.responseText;
            }
        });
    }
});


// System properties - exclude updates of properties
function renderPropertyGrid(jsonObj) {
    Ext.getDom("panel-properties").innerHTML = "";
    var resourceObj = {};
    if (jsonObj["created-at"]) {
        resourceObj["created"] = jsonObj["created-at"];
    }
    if (jsonObj["created-by"]) {
        resourceObj["created-by"] = jsonObj["created-by"];
        var created_by = jsonObj["created-by"];
        //Ext.getDom("main-content-folder-owner").innerHTML = "";
        //var ownerDiv = Ext.getDom("main-content-folder-owner");
        //Ext.DomHelper.insertHtml("beforeEnd", ownerDiv, "owner: " + created_by);

    }
    if (jsonObj["last-modified-at"]) {
        resourceObj["last-modified"] = jsonObj["last-modified-at"];
    }
    if (jsonObj["last-modified-by"]) {
        resourceObj["last-modified-by"] = jsonObj["last-modified-by"];
    }
    if (jsonObj["mimeType"]) {
        resourceObj["mimeType"] = jsonObj["mimeType"];
    }
    resourceObj["url"] = jsonObj["host-url"] + jsonObj["uri"];
    var propertyGrid = new Ext.grid.PropertyGrid({
        renderTo: "panel-properties",
        autoHeight: true,
        //autoWidth: true,
        width: 320,
        disableSelection: true,
        startEditing: Ext.emptyFn,
        source: resourceObj
    });
    propertyGrid.render();
}

var aclPanel = {
    id: "panel-acl-control",
    title: "Sharing",
    bodyStyle: "padding-bottom:15px; background:#eee;",
    autoScroll: true,
    contentEl: "panel-acl"
};

var metaPanel = new Ext.Panel({
    layout: "accordion",
    id: "layout-meta",
    title: "Systems Genetics:MetaViews",
    region:"east",
    border: true,
    split:true,
    margins: "2 5 5 0",
    width: 320,
    minSize: 100,
    maxSize: 500,
    collapsible: true,
    collapsed: true,
    layoutConfig: {
        titleCollapse: true,
        hideCollapseTool: true,
        animate: true,
        activeOnTop: false
    },
    items: [labelsPanel, propertiesPanel, annotationsPanel, aclPanel]
});
